﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.Xml;
namespace lingopen
{
    /// <summary>
    /// 静态扩展
    /// </summary>
    public static class Extentions
    {

        public static void Log(this string log)
        {
            Console.WriteLine(log);
        }
        /// <summary>
        /// 转换为json格式
        /// </summary>
        /// <param name="entity">实体对象</param>
        /// <returns></returns>
        public static string ToJson(this object entity, NullValueHandling nullValueHandling = NullValueHandling.Ignore)
        {
            return JsonConvert.SerializeObject(entity, Newtonsoft.Json.Formatting.Indented, new JsonSerializerSettings { NullValueHandling = nullValueHandling });
        }
        /// <summary>
        /// 转换为对象 T
        /// </summary>
        /// <typeparam name="T">返回值类型</typeparam>
        /// <param name="json">json数据</param>
        /// <returns></returns>
        public static T FromJson<T>(this string json)
        {
            return JsonConvert.DeserializeObject<T>(json);
        }
        /// <summary>
        /// 是否不为空
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static bool IsNotNull(this string str)
        {
            return !string.IsNullOrEmpty(str);
        }

        public static bool ListIsNull<T>(this List<T> list)
        {
            return list == null || list.Count < 1;
        }
        public static bool IsNull(this string str)
        {
            return string.IsNullOrEmpty(str);
        }

        


        private static string[] strs = new string[]
                                 {
                                  "a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z",
                                  "A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"
                                 };
        /// <summary>
        /// 创建随机字符串
        ///本代码来自开源微信SDK项目：https://github.com/night-king/weixinSDK
        /// </summary>
        /// <returns></returns>
        public static string CreateNoncestr()
        {
            Random r = new Random();
            var sb = new StringBuilder();
            var length = strs.Length;
            for (int i = 0; i < 15; i++)
            {
                sb.Append(strs[r.Next(length - 1)]);
            }
            return sb.ToString();
        }
        /// <summary>  
        /// SHA1 加密，返回大写字符串  
        /// </summary>  
        /// <param name="content">需要加密字符串</param>  
        /// <returns>返回40位UTF8 大写</returns>  
        public static string ToSHA1(this string content)
        {
            //建立SHA1对象
            SHA1 sha = new SHA1CryptoServiceProvider();
            //将mystr转换成byte[]
            ASCIIEncoding enc = new ASCIIEncoding();
            byte[] dataToHash = enc.GetBytes(content);
            //Hash运算
            byte[] dataHashed = sha.ComputeHash(dataToHash);
            //将运算结果转换成string
            string hash = BitConverter.ToString(dataHashed).Replace("-", "");
            return hash; 
        }
        ///// <summary>  
        ///// SHA1 加密，返回大写字符串  
        ///// </summary>  
        ///// <param name="content">需要加密字符串</param>  
        ///// <param name="encode">指定加密编码</param>  
        ///// <returns>返回字符串</returns>  
        //public static string SHA1(this string content, Encoding encode)
        //{
        //    try
        //    {
        //        SHA1 sha1 = new SHA1CryptoServiceProvider();
        //        byte[] bytes_in = encode.GetBytes(content);
        //        byte[] bytes_out = sha1.ComputeHash(bytes_in);
        //        sha1.Dispose();
        //        string result = String.Join("", bytes_out.Select(o => o.ToString("x2")));
        //        return result;
        //    }
        //    catch (Exception ex)
        //    {
        //        throw new Exception("SHA1加密出错：" + ex.Message);
        //    }
        //}

        /// <summary>
        /// 获取时间戳
        /// </summary> 
        public static int ToDateTimeInt(this DateTime time)
        {
            DateTime date1 = new DateTime(1970, 1, 1);
            DateTime startTime = TimeZoneInfo.ConvertTimeToUtc(date1, TimeZoneInfo.Local);
            return (int)(time - startTime).TotalSeconds;
        }
        public static DateTime ToDateTime(this long timeStamp)
        {
            timeStamp = timeStamp * 1000;
            DateTime date1 = new DateTime(1970, 1, 1);
            DateTime startTime = TimeZoneInfo.ConvertTimeToUtc(date1, TimeZoneInfo.Local);
            DateTime dt = startTime.AddMilliseconds(timeStamp);
            return dt;
        }

        /// <summary>  
        /// 获取文件的MD5码  
        /// </summary>  
        /// <param name="fileName">传入的文件名（含路径及后缀名）</param>  
        /// <returns></returns>  
        public static string GetMD5HashFromFile(this string fileName)
        {
            try
            {
                FileStream file = new FileStream(fileName, System.IO.FileMode.Open);
                MD5 md5 = new MD5CryptoServiceProvider();
                byte[] retVal = md5.ComputeHash(file);
                file.Close();
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < retVal.Length; i++)
                {
                    sb.Append(retVal[i].ToString("x2"));
                }
                return sb.ToString();
            }
            catch (Exception ex)
            {
                throw new Exception("GetMD5HashFromFile() fail,error:" + ex.Message);
            }
        }

    }


    /// <summary>
    /// xml体转换器
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class XmlEntityExchange<T> where T : new()
    {
        /// <summary>
        /// 将XML转换为对象
        /// </summary>
        /// <param name="xml"></param>
        /// <returns></returns>
        public static T ConvertXml2Entity(string xml)
        {
            try
            {
                XmlDocument doc = new XmlDocument();
                PropertyInfo[] propinfos = null;
                doc.LoadXml(xml);
                XmlNodeList nodelist = doc.SelectNodes("/xml");
                T entity = new T();
                foreach (XmlNode node in nodelist)
                {
                    //初始化propertyinfo
                    if (propinfos == null)
                    {
                        Type objtype = entity.GetType();
                        propinfos = objtype.GetProperties();
                    }
                    //填充entity类的属性
                    foreach (PropertyInfo pi in propinfos)
                    {
                        XmlNode cnode = node.SelectSingleNode(pi.Name);
                        pi.SetValue(entity, Convert.ChangeType(cnode.InnerText, pi.PropertyType), null);
                    }
                }
                return entity;
            }
            catch (Exception)
            {

                return default(T);
            }
        }

        /// <summary>
        /// 构造微信消息
        /// </summary>
        /// <param name="t">对象实体</param>
        /// <returns>返回微信消息xml格式</returns>
        public static string ConvertEntity2Xml(T t)
        {
            try
            {


                StringBuilder builder = new StringBuilder();
                builder.Append("<xml>");
                Type objtype = t.GetType();
                //填充entity类的属性
                foreach (PropertyInfo pi in objtype.GetProperties())
                {
                    object obj = pi.GetValue(t);
                    string value = obj == null ? "" : obj.ToString();
                    if (pi.PropertyType.Name.ToLower() == "int64")
                        builder.Append("<" + pi.Name + ">" + value + "</" + pi.Name + ">");
                    else
                        builder.Append("<" + pi.Name + "><![CDATA[" + value + "]]></" + pi.Name + ">");
                }
                builder.Append("</xml>");
                return builder.ToString();
            }
            catch (Exception)
            {
                return "";
            }
        }
    }

}
